# app/api/salary.py

from flask import Blueprint, request, current_app, render_template
from flask_restful import Api, Resource
from app.services.salary_service import SalaryService
from app.utils.response import success_response, error_response
from werkzeug.utils import secure_filename
import os
import pandas as pd

salary_bp = Blueprint('salary', __name__)
api = Api(salary_bp)

class SalaryResource(Resource):
    """单条薪资：GET/PATCH/PUT/DELETE"""
    """GET /salaries/<id>"""
    def get(self, salary_id):
        try:
            s = SalaryService.get_salary(salary_id)
            if not s:
                return error_response('记录不存在', 404)
            return success_response(s.to_dict())
        except Exception as e:
            return error_response(str(e), 500)

    def patch(self, salary_id):
        """PATCH /salaries/<id> 部分更新"""
        try:
            data = request.get_json()
            s = SalaryService.update_salary(salary_id, data)
            return success_response(s.to_dict())
        except Exception as e:
            return error_response(str(e), 500)

    def put(self, salary_id):
        """PUT /salaries/<id> 全量替换"""
        try:
            data = request.get_json()
            s = SalaryService.replace_salary(salary_id, data)
            return success_response(s.to_dict())
        except Exception as e:
            return error_response(str(e), 500)

    def delete(self, salary_id):
        """DELETE /salaries/<id>"""
        try:
            SalaryService.delete_salary(salary_id)
            return success_response(f'ID={salary_id} 已删除')
        except Exception as e:
            return error_response(str(e), 500)


class SalaryListResource(Resource):
    """列表 & 单条创建：GET / POST"""
    def get(self):
        try:
            page = request.args.get('page', 1, type=int)
            per_page = request.args.get('per_page', 10, type=int)
            filters = {
                'keyword': request.args.get('keyword'),
                'company': request.args.get('company'),
                'position': request.args.get('position'),
                'city': request.args.get('city'),
                'min_salary': request.args.get('min_salary', type=float),
                'max_salary': request.args.get('max_salary', type=float),
                'education': request.args.get('education'),
                'type': request.args.get('type'),
                'status': request.args.get('status'),
            }
            data = SalaryService.page(filters, page, per_page)
            return success_response(data)
        except Exception as e:
            return error_response(str(e), 500)

    def post(self):
        """POST /salaries create()"""
        try:
            data = request.get_json()
            s = SalaryService.create_salary(data)
            return success_response(s.to_dict(), 201)
        except Exception as e:
            return error_response(str(e), 500)


class SalaryBatchResource(Resource):
    """批量 JSON 上传接口"""
    def post(self):
        try:
            arr = request.get_json()
            if not isinstance(arr, list):
                return error_response('请提交 JSON 数组', 400)
            objs = SalaryService.batch_create_salaries(arr)
            return success_response([o.to_dict() for o in objs], 201)
        except Exception as e:
            return error_response(str(e), 500)


@salary_bp.route('/upload', methods=['GET', 'POST'])
def upload_excel():
    """
    批量上传 Excel：
      - GET: 渲染上传表单
      - POST: 解析 .xls/.xlsx，并转到预览页面
    """
    if request.method == 'GET':
        return render_template('upload.html')

    # POST 处理
    if 'file' not in request.files:
        return render_template('upload.html', error='未上传文件')
    file = request.files['file']
    if file.filename == '':
        return render_template('upload.html', error='请选择文件')

    # 管理员密码校验
    admin_pw = request.form.get('admin_password', '')
    if not SalaryService.verify_admin(admin_pw):
        return render_template('upload.html', error='管理员密码错误')

    # 保存临时文件
    filename = secure_filename(file.filename)
    folder = current_app.config['UPLOAD_FOLDER']
    os.makedirs(folder, exist_ok=True)
    path = os.path.join(folder, filename)
    file.save(path)

    # 按文件后缀选择 engine 解析
    ext = os.path.splitext(filename)[1].lower()
    try:
        if ext == '.xlsx':
            df = pd.read_excel(path, engine='openpyxl')
        elif ext == '.xls':
            df = pd.read_excel(path, engine='xlrd')
        else:
            return render_template('upload.html',
                                   error='不支持的文件格式，请上传 .xls 或 .xlsx')
    except ImportError as e:
        return render_template('upload.html',
                               error=f'缺少依赖库：{e}，请执行 pip install openpyxl xlrd')
    except Exception as e:
        return render_template('upload.html',
                               error=f'解析 Excel 失败：{e}')

    # 将 DataFrame 转为 dict 列表
    data_list = []
    for _, row in df.iterrows():
        data_list.append({
            'company': row.get('公司'),
            'position': row.get('职位'),
            'city': row.get('城市'),
            'base_salary': row.get('月薪(k)'),
            'months': row.get('月数'),
            'bonus': row.get('年终奖(k)'),
            'signing_bonus': row.get('签字费(k)'),
            'stock': row.get('股票期权'),
            'type': row.get('类型'),
            'education': row.get('学历要求'),
            'industry': row.get('行业'),
            'remark': row.get('备注'),
        })

    # 渲染预览并可编辑页面
    return render_template('preview.html',
                           data_list=data_list,
                           row_count=len(data_list))



@salary_bp.route('/upload/confirm', methods=['POST'])
def confirm_upload():
    """
    确认上传：读取表单里用户编辑后的数据，补充 user_id=0 后批量写库
    """
    try:
        count = int(request.form.get('row_count', 0))
        data_list = []
        for i in range(count):
            item = {
                'company':        request.form.get(f'company-{i}'),
                'position':       request.form.get(f'position-{i}'),
                'city':           request.form.get(f'city-{i}'),
                'base_salary':    float(request.form.get(f'base_salary-{i}', 0) or 0),
                'months':         int(request.form.get(f'months-{i}', 0) or 0),
                'bonus':          float(request.form.get(f'bonus-{i}', 0) or 0),
                'signing_bonus':  float(request.form.get(f'signing_bonus-{i}', 0) or 0),
                'stock':          request.form.get(f'stock-{i}'),
                'type':           request.form.get(f'type-{i}'),
                'education':      request.form.get(f'education-{i}'),
                'industry':       request.form.get(f'industry-{i}'),
                'remark':         request.form.get(f'remark-{i}'),
                # 新增 user_id 字段，管理员批量导入可统一用 0 或其他占位
                'user_id':        0,
                # 状态默认 pending
                'status':         'pending'
            }
            data_list.append(item)

        objs = SalaryService.batch_create_salaries(data_list)
        return render_template('upload_success.html', count=len(objs))
    except Exception as e:
        current_app.logger.error(f"确认上传出错：{e}")
        # 回传空列表和错误，仍跳回预览页
        return render_template('preview.html',
                               data_list=[], row_count=0,
                               error=f"上传失败：{e}")


# 注册资源
api.add_resource(SalaryResource, '/salaries/<int:salary_id>')
api.add_resource(SalaryListResource, '/salaries')
api.add_resource(SalaryBatchResource, '/salaries/batch')